<?php
class Solvex_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
	/**
	 * 1st implement the environment
	 *  - set the timezone to UTC
	 *  - register the apphost
	 */
	protected function _initEnvironment()
	{
		date_default_timezone_set('UTC');
		if(isset($_SERVER['HTTP_HOST'])){
			if($_SERVER['HTTP_HOST'] === '127.0.0.1'){
				$domainHost = 'localhost';
			} else {
				$domainParts = explode('.', $_SERVER['HTTP_HOST']);
				if(count($domainParts) === 1){
					$domainHost = $domainParts[0];
				} elseif($domainParts === 2){
					$domainHost = $domainParts[0] . '_' . $domainParts[1];
				} elseif($domainParts === 3){
					$domainHost = $domainParts[1] . '_' . $domainParts[2];
				}
			}
			Zend_Registry::set('apphost', strtolower($domainHost));
		} else {
			throw new Solvex_Exception("Cannot continue - missing HTTP_HOST from SERVER Superglobals.");
		}
	}
	
	/**
	 * 2nd - Init autoloading
	 */
	protected function _initLoader()
	{
		$this->bootstrap('Environment');
		$loader = Zend_Loader_Autoloader::getInstance();
		$loader->setFallbackAutoloader(true);
		$loader->suppressNotFoundWarnings(false);
		$loader->registerNamespace('Solvex_');
		$loader->registerNamespace('Zym_');
		$loader->registerNamespace('ZFDebug_');
		
		// use the apphost name and if not existent use the default name
		$modulesPath = MODULES_PATH . '/' . Zend_Registry::get('apphost');
		if(!is_dir($modulesPath) || !is_readable($modulesPath)){
			$modulesPath = MODULES_PATH . '/default';
		}
		try {
			$dir = new DirectoryIterator($modulesPath);
		} catch(Exception $e){
			throw new Solvex_Exception("No modules path available.");
		}
		
		foreach($dir as $file){
			if($file->isDot() || !$file->isDir()){
				continue;
			}
			
			$module = $file->getFilename();
			
			if(Solvex_Tool_Filesystem::isSCCSDirectory($module)){
				continue;
			}
			
			new Zend_Application_Module_Autoloader(array(
				'namespace' => ucfirst($module) . '_',
				'basePath'  => $file->getPathname()
			));
		}	
	}
	
	protected function _initApplication()
	{
		$this->bootstrap('Loader');
		Zend_Registry::set('app', $this->getApplication());
		return Zend_Registry::get('app');
	}
	
	protected function _initConfig()
	{
		$configFile = APPLICATION_PATH . '/configs/' . Zend_Registry::get('apphost') . '/application.xml';
		if(!is_file($configFile) || !is_readable($configFile)){
			$configFile = APPLICATION_PATH . '/configs/default/application.xml';
			Zend_Registry::set('apphost', 'default');
		}
		Zend_Registry::set('config', new Zend_Config_Xml($configFile,APPLICATION_ENV));
		return Zend_Registry::get('config');
	}
	
	protected function _initCache()
	{
		$this->bootstrap('Application');
		
		$cacheDir = ROOT_PATH . '/data/cache';
		if(!is_readable($cacheDir)){
			mkdir($cacheDir, 0777);
		} elseif(!is_writable($cacheDir)){
			chmod($cacheDir, 0777);
		}
		if (!is_writable($cacheDir)) {
        	echo "Cache directory should be writable. Run 'chmod -R 0777 $cacheDir'";
            exit();
        }
		
        $lifetime = Zend_Registry::get('config')->system->cache->options->frontend->lifetime;
		
        $backendOptions = array(
            'cache_dir'                 => $cacheDir,
            'hashed_directory_level'    => 1,
            'file_name_prefix'          => 'solvex_cache',
            'hashed_directory_umask'    => 0777
        );
        $frontendOptions = array(
			'cache_id_prefix'			=>	Zend_Registry::get('apphost'),
			'lifetime'					=>  $lifetime,
			'automatic_serialization'	=>  true
		);
		Zend_Registry::set('cache', Zend_Cache::factory(
        	'Core', 'File',
            $frontendOptions,
            $backendOptions,
            false,
            true
        ));
        return Zend_Registry::get('cache');
	}
	
	protected function _initDbAdapter()
	{
		$config = Zend_Registry::get('config')->system->database;
		$db = Zend_Db::factory($config->adapter, array(
			'username' => $config->username,
			'password' => $config->password,
			'host'     => $config->host,
			'dbname'   => $config->dbname
		));
		Zend_Db_Table_Abstract::setDefaultAdapter($db);
		Zend_Db_Table_Abstract::setDefaultMetadataCache(Zend_Registry::get('cache'));
		Zend_Registry::set('db', $db);
		return Zend_Registry::get('db');
	}
	
	protected function _initSite()
	{
		$db = Zend_Db_Table_Abstract::getDefaultAdapter();
		$db->setFetchMode(Zend_Db::FETCH_OBJ);
		$select = $db->select();
		$select->from('website')
			   ->where('hostname = ?', Zend_Registry::get('apphost'));
		$row = $db->fetchRow($select);
		$site = new Solvex_Website();
		$site->setId($row->id);
		$site->setName($row->name);
		Zend_Registry::set('site', $site);
		return Zend_Registry::get('site');	
	}
	
	protected function _initFrontController()
	{
		$front = Zend_Controller_Front::getInstance();
		$path = MODULES_PATH . '/' . Zend_Registry::get('apphost');
		if(!is_dir($path) || !is_readable($path)){
			$path = MODULES_PATH . '/default';
		}
		$front->addModuleDirectory($path);
		$front->setDefaultModule('core');
		$front->setParam('prefixDefaultModule', true);
		$front->registerPlugin(new Solvex_Controller_Plugin_ViewSetup(), 30);
		return $front;
	}
	
	protected function _initView()
	{
		$view = new Zym_View();
		$view->addHelperPath('Solvex/View/Helper','Solvex_View_Helper');
		$view->addFilterPath('Solvex/View/Filter','Solvex_View_Filter');
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
		$viewRenderer->setView($view);
		return $view;	
	}
	
	protected function _initLayout()
	{
		$path = TEMPLATES_PATH . '/' . Zend_Registry::get('apphost'); 
		if(!is_dir($path) || !is_readable($path)){
			$path = TEMPLATES_PATH . '/default';
		}
		$path .= '/' . Zend_Registry::get('config')->web->design->template . '/layouts/';
		$layout = Zend_Layout::startMvc(array(
			'layout' => 'default',
			'layoutPath' => $path,
			'contentKey' => 'content'
		));
		return $layout;
	}
}